package com.yz.crm.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yz.crm.passport.constant.PassportConst;
import com.yz.crm.passport.model.SessionUser;

/**
 * Created by DOVE on 2017/5/15 0015.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
    private static Log log = LogFactory.getLog(LoginInterceptor.class);
    
    /**默认登录URL*/
    private static final String DEFAULT_LOGIN_URL = "/passport/login";
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        SessionUser user = (SessionUser) session.getAttribute(PassportConst.SESSION_KEY_USER);
        if (user == null) {
            String requestType = request.getHeader("X-Requested-With");
            if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
                response.addHeader("loginStatus", "accessDenied");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                response.sendRedirect(request.getContextPath() + DEFAULT_LOGIN_URL);
            }
            return false;
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

}
